import React, { Component } from 'react';
import { getBlob } from '@/utils/requestUtil';

export default class AuthImg extends Component {

    constructor(props) {
        super(props)
        this.state = {
            src: ''
        }
    }

    async componentDidMount() {
        const { authSrc } = this.props
        const blob = await getBlob(authSrc);
        if (blob) {
            this.updateURL(blob);
        }
    }

    async componentDidUpdate(prevProps) {
        const { authSrc } = this.props
        if (authSrc !== prevProps.authSrc) {
            this.setState({ src: '' });
            const blob = await getBlob(authSrc);
            if (blob) {
                this.updateURL(blob);
            }
        }
    }

    async componentWillUnmount() {
        const { src } = this.state;
        if (src) {
            URL.revokeObjectURL(src);
        }
    }

    updateURL = (blob) => {
        const { src } = this.state;
        if (src) {
            URL.revokeObjectURL(src);
        }
        this.setState({ src: URL.createObjectURL(blob) });
    }
    render() {
        const { src } = this.state;
        if (!src) return '图片加载中...';
        return (
            <img
                alt=''
                {...this.props}
                src={src}
            ></img>
        )
    }
}
